import { Request, valiMobile, errorToast, successToast, checkPermission, parseTime, getUserRole } from '@/utils'
import { connectStatus, allotStatus, networkTypeList, payType } from '@/config'
import md5 from 'md5'
import cascader from '@/components/cascader.vue'
import mselect from '@/components/mselect.vue'
let request = new Request()

export default {
	data () {
		return {
			role : 0,
			deviceId : 0,
			formData : {
				device_type : '',
				charge_mode : '',
				port_number : '',
				sim_iccid : '',
				agent_id : '',
				coin_limit : '',
				price_id : '',
				gateway : '',
				network_type : '',
				sim_fee : '',
				sim_expire : '',
				device_name : '',
				province_id : '',
				city_id     : '',
				district_id : '',
				address : '',
				//longitude : '',
				//latitude  : '',
				remarks : ''
			},
			
			copyData : {},
			
			priceList : [],
			deviceTypes : [],
			gatewayList : [],
			networkTypes : networkTypeList,
			agentList : [],
			
			rules : {
				device_type : {
					required : true,
					message : '请选择设备类型'
				},
				charge_mode : {
					required : true,
					message : '请选择设备类型'
				},
				sim_iccid : {
					required : true,
					message : '请填写SIM ICCID'
				},
				port_number : {
					required : true,
					message : '请填写端口数'
				},
				gateway : {
					required : true,
					message : '请选择网关'
				},
			}
		}
	},
	
	components : {
		cascader,
		mselect
	},
	
	methods : {
		checkPermission : checkPermission,
		
		submit : function(){
			this.$refs.form.validate(validate => {
				if(!validate){
					return
				}
				
				let formData = Object.assign({}, this.formData)
				let deviceId = this.deviceId
				if(deviceId > 0) {
					formData.device_id = deviceId
				}
				
				request.post('device/save', res => {
					if(res.success) {
						successToast(res.msg, this)
						this.$router.go(-1)
					}else{
						errorToast(res.msg, this)
					}
				}, formData)
				
			})
		}
	},
	
	watch : {
		'formData.enable' : function(value){
			this.$set(this.formData, 'status', value ? 1 : 0)
		}
	},
	
	created () {
		this.role = getUserRole() //角色
		
		
		request.setMany(true)
		
		request.get('agent/dropSelect', res => { //获取代理商
			this.agentList = res.data
		})
		
		request.get('price/dropSelect', res => { //获取价格套餐
			this.priceList = res.data
		})

		request.get('gateway/dropSelect', res => { //获取网关
			this.gatewayList = res.data
		})
		
		let deviceId = this.$route.params.deviceId || 0
		if(deviceId > 0){ //编辑
			this.deviceId = deviceId
			request.get('device/getEditInfo', res => {
				if(res.success) {
					let data = res.data
					for(let k in data) {
						if(k in this.formData) {
							if(k === 'sim_expire'){
								data[k] = parseTime(data[k], '{y}-{m}-{d}')
								console.log(data[k])
							}
							this.formData[k] = data[k] || ''
						}
					}
				}else{
					errorToast(res.msg, this)
				}

			}, {id : deviceId})
		}
		
		
		
		request.setMany(false)
		
	}
}